package com.lanou.tipsy.activity;

import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;
import com.lanou.tipsy.MusicIdle;
import com.lanou.tipsy.R;
import com.lanou.tipsy.adapter.playerLists.LocalListAdapter;
import com.lanou.tipsy.adapter.playerLists.MainListAdapter;
import com.lanou.tipsy.base.BaseActivity;
import com.lanou.tipsy.broadcastReceiver.NotificationRecevier;
import com.lanou.tipsy.data.MyEventBus;
import com.lanou.tipsy.entity.playerList.personal.PersonalList;
import com.lanou.tipsy.fragment.main.MainFragment;
import com.lanou.tipsy.service.MyService;
import com.lanou.tipsy.tools.cache.DataCleanManager;
import com.lanou.tipsy.tools.fragment_back.BackHandledFragment;
import com.lanou.tipsy.tools.fragment_back.BackHandledInterface;
import com.lanou.tipsy.tools.volley.VolleySingleton;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners;
import com.umeng.socialize.sso.UMSsoHandler;

import java.util.ArrayList;
import java.util.Calendar;

import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;

/**
 * Created by fj on 15/10/23.
 * 主页
 */
public class MainActivity extends BaseActivity implements BackHandledInterface, View.OnClickListener {
    public static final String TAG = "MainActivity";
    private BackHandledFragment mBackHandedFragment;

    private LinearLayout setTheme, upData, cacheClear, login, exit,timer,about;//侧拉菜单上得各种按钮

    //播放歌曲
    private ListView songListLv;//歌曲列表
    private TextView listSizeTv, cacheData;//歌曲列表长度
    private CardView cardView;
    private ImageView playerIv, nextIv, songListIv;//播放,下一首,歌曲列表
    private ImageView imageView;//设置正在播放的歌曲的图片
    private TextView songTv, singerTv;//设置正在播放的歌曲的歌名和歌手名
    private int position;//当前播放的音乐的position
    private TextView progressTv, maxTv;
    //我的歌曲列表
    private ArrayList<PersonalList> songsLists;//集合
    private PersonalList songsList;//实体类
    private MainListAdapter adapter;//适配器
    //网络
    private VolleySingleton volleySingleton;
    private ImageLoader imageLoader;//加载图片
    //service
    private MusicIdle musicIdle;
    private Context mContext;
    private String string;
    private Button exitAccount, exitProgram;
    private android.app.AlertDialog exitDialog; //退出键弹出提示框
    private TextView userNm; //用户名
    private ImageView userIc; //用户头像
    private UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.login");
    public static int requestCode = 100;
    private LinearLayout mainMenu; //个人信息布局
    private String userIcon, userName;//缓存内的用户名,头像URL
    public String icon, name;  //登录获取的用户名,头像URL

    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicIdle = MusicIdle.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    private Intent intent;
    private Bitmap bitmap;//本地歌曲图片
    private String pictureUrl;//网络歌曲图片
    private String tag;//区分本地歌曲和网络歌曲

    /**
     * 定时关机
     */
    private TextView ensureButton = null;
    private TextView cancelButton = null;
    private TimePicker timePicker = null;

    CountDownTimer countDownTimer = null;

    // 选定关闭小时
    int closeHour = 0;
    // 选定关闭分钟
    int closeMinutes = 0;
    Calendar c = null;
    private NotificationRecevier receiver;

    /**
     *
     */


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //ThemeMemory.onActivityCreateSetTheme(this);
        //去掉标题栏
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //绑定服务
        intent = new Intent(this, MyService.class);
        startService(intent);//运行服务
        bindService(intent, conn, BIND_AUTO_CREATE);//绑定服务
        EventBus.getDefault().register(this);
        initView();


        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.fl_main, new MainFragment());
        transaction.commit();

        setTheme = (LinearLayout) findViewById(R.id.setTheme);
        upData = (LinearLayout) findViewById(R.id.upData);
        setTheme.setOnClickListener(this);
        upData.setOnClickListener(this);

        receiver = new NotificationRecevier();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(NotificationRecevier.NOTIFICATION_ITEM_BUTTON_LAST);
        intentFilter.addAction(NotificationRecevier.NOTIFICATION_ITEM_BUTTON_NEXT);
        intentFilter.addAction(NotificationRecevier.NOTIFICATION_ITEM_BUTTON_PLAY);
        intentFilter.addAction(NotificationRecevier.NOTIFICATION_ITEM_BUTTON_DELETE);
        registerReceiver(receiver, intentFilter);

    }

    @Override
    public void onResume() {
        super.onResume();
        //获取当前缓存大小
        try {
            string = DataCleanManager.getCacheSize(getCacheDir());
            Log.i("test", TAG + "首次启动缓存:" + string);
            //cacheData.setText(string);
        } catch (Exception e) {
            e.printStackTrace();
        }
        JPushInterface.onResume(this);
    }

    //初始化控件->添加监听
    private void initView() {
        //跳转页面
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.fl_main, new MainFragment());
        transaction.commit();

        //初始化->监听
        setTheme = (LinearLayout) findViewById(R.id.setTheme);
        upData = (LinearLayout) findViewById(R.id.upData);
        setTheme.setOnClickListener(this);
        upData.setOnClickListener(this);

        volleySingleton = VolleySingleton.getInstance();
        imageLoader = volleySingleton.getImageLoader();
        playerIv = (ImageView) findViewById(R.id.iv_player);
        nextIv = (ImageView) findViewById(R.id.iv_next);
        songListIv = (ImageView) findViewById(R.id.iv_songs_list);
        singerTv = (TextView) findViewById(R.id.tv_singing_singer);
        songTv = (TextView) findViewById(R.id.tv_singing_songs);
        imageView = (ImageView) findViewById(R.id.iv_singing_picture);
        cardView = (CardView) findViewById(R.id.cd_singing_root);
        progressTv = (TextView) findViewById(R.id.tv_time_progress);
        maxTv = (TextView) findViewById(R.id.tv_time_max);
        cacheClear = (LinearLayout) findViewById(R.id.cacheClear);
        userIc = (ImageView) findViewById(R.id.userIc);
        userNm = (TextView) findViewById(R.id.userName);
        login = (LinearLayout) findViewById(R.id.login);
        exit = (LinearLayout) findViewById(R.id.exit);
        mainMenu = (LinearLayout) findViewById(R.id.mainMenu);
        timer = (LinearLayout) findViewById(R.id.timer);
        about = (LinearLayout) findViewById(R.id.about);
        //全部分类按钮监听
        mainMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        //点击跳转
        cardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (musicIdle.isPlaying()) {
                        Intent intent = new Intent(MainActivity.this, PlayerActivity.class);
                        startActivity(intent);
                        overridePendingTransition(R.anim.translate_ve_in, R.anim.translate_ve_out);

                    } else {
                        Toast.makeText(MainActivity.this, "当前没有歌曲正在播放哦~~", Toast.LENGTH_SHORT).show();
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });
        playerIv.setOnClickListener(this);
        nextIv.setOnClickListener(this);
        songListIv.setOnClickListener(this);
        cacheClear.setOnClickListener(this);
        login.setOnClickListener(this);
        exit.setOnClickListener(this);
        timer.setOnClickListener(this);
        about.setOnClickListener(this);
    }


    @Override
    public void setSelectedFragment(BackHandledFragment selectedFragment) {
        this.mBackHandedFragment = selectedFragment;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (mBackHandedFragment == null || !mBackHandedFragment.onBackPressed()) {
            if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
                super.onBackPressed();
            } else {
                getSupportFragmentManager().popBackStack();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.about:
                Intent intent2 = new Intent(this,AboutActivity.class);
                startActivity(intent2);
                break;
            //主题设置
            case R.id.setTheme:
                Intent intent = new Intent(this, ThemeSettingActivity.class);
                startActivity(intent);
                this.overridePendingTransition(R.anim.translate_enter_in, R.anim.translate_enter_out);
                //finish();
                break;
            //更新
            case R.id.upData:
                final ProgressDialog progressDialog = new ProgressDialog(this);
                progressDialog.setTitle("检查更新");
                progressDialog.setMessage("版本更新中...");
                progressDialog.show();
                //延时执行
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        progressDialog.dismiss();
                        Toast.makeText(MainActivity.this, "当前已是最新版本", Toast.LENGTH_LONG).show();
                    }
                }, 2000);
                break;
            //登录
            case R.id.login:
                if (userIcon == "0" && userName == "0") {
                    Toast.makeText(mContext, "请先登录", Toast.LENGTH_SHORT).show();
                } else {
                    Intent intent1 = new Intent(this, LoginActivity.class);
                    startActivityForResult(intent1, requestCode);
                }
                break;
            //清理缓存
            case R.id.cacheClear:
                final AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("醉音乐");
                builder.setIcon(R.mipmap.cache_data_dialog);
                onResume();
                builder.setMessage("清空缓存?  (" + string + ")");

                builder.setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        DataCleanManager.deleteFolderFile(getCacheDir().toString(), true);
                        try {
                            String s = DataCleanManager.getCacheSize(getCacheDir());
                            cacheData.setText(s);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                builder.create().show();
                break;
            //定时关闭程序
            case R.id.timer:
                alertDialog();
                break;
            //退出
            case R.id.exit:
                exitApp();
                break;
            //播放
            case R.id.iv_player:
                play();
                break;
            //下一首
            case R.id.iv_next:
                next();
                break;
            //歌单
            case R.id.iv_songs_list:
                songsListpopupWindow();
                break;
        }
    }

    //登录后获取用户头像和昵称信息

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 使用SSO授权
         */
        UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode);
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
        if (requestCode == 100 && resultCode == 100) {
            icon = data.getStringExtra("profile_image_url");
            name = data.getStringExtra("screen_name");
            Log.i("test", TAG + icon);
            Log.i("test", TAG + name);
            imageLoader = VolleySingleton.getInstance().getImageLoader();
            ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(userIc, R.mipmap.ic_launcher, R.mipmap.ic_launcher);
            imageLoader.get(icon, imageListener);
            userNm.setText(name);
        }
    }


    //获得当前正在播放的歌曲的position
    public void onEvent(MyEventBus.ListPosition index) {
        this.position = index.getIndex();
    }

    //onEvent->我的歌曲列表
    public void onEvent(MyEventBus.PersonalLists personalLists) {
//        Log.i("Sysout", "MainActivity->getEvent");
        this.songsLists = personalLists.getPersonalLists();
    }

    //获得本地歌曲的图片uri
    public void onEvent(MyEventBus.SetLocalPicture picture) {
        bitmap = picture.getImageUri();
    }

    //获得网络歌曲的图片url
    public void onEvent(MyEventBus.SetNetPitcure picture) {
        pictureUrl = picture.getImageUrl();
    }

    //获得歌曲名字,歌手,tag
    public void onEvent(MyEventBus.SetSongInfo songInfo) {
        songTv.setText(songInfo.getSongs());
        singerTv.setText(songInfo.getSinger());
        tag = songInfo.getTag();
        if (tag.equals("本地歌曲")) {
            imageView.setImageBitmap(bitmap);
        } else if (tag.equals("网络歌曲")) {
            ImageLoader.ImageListener listener = ImageLoader.getImageListener(imageView,
                    R.mipmap.logo_2, R.mipmap.error);
            imageLoader.get(pictureUrl, listener);
        }
    }


    //popupWindow->歌曲列表
    private void songsListpopupWindow() {
        //加载布局文件
        final PopupWindow popupWindow = new PopupWindow(this);
        //加载布局文件
        View view = getLayoutInflater().inflate(R.layout.fr_personal_lists, null);
        songListLv = (ListView) view.findViewById(R.id.lv_personal_lists);
        listSizeTv = (TextView) view.findViewById(R.id.tv_personal_size);
        if (songsLists != null && songsLists.size() > 0) {
            listSizeTv.setText("/" + songsLists.size() + "首");//设置歌曲列表长度
        } else {
            listSizeTv.setVisibility(View.GONE);
        }
        adapter = new MainListAdapter(songsLists, MainActivity.this, position);
        songListLv.setAdapter(adapter);
        songListLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                songsList = (PersonalList) parent.getItemAtPosition(position);
                Toast.makeText(MainActivity.this, songsList.getSongTitle(), Toast.LENGTH_SHORT).show();
                EventBus.getDefault().post(new MyEventBus.NetSongs(adapter.getDatas(), position));
                popupWindow.dismiss();
            }
        });
        popupWindow.setContentView(view);
        popupWindow.setWidth(ActionBar.LayoutParams.MATCH_PARENT);
        //距离底部高度
        popupWindow.setHeight(500);
        //设置非popuWindow区域可出
        popupWindow.setOutsideTouchable(true);
        //设置是否可以获得焦点
        popupWindow.setFocusable(true);
        //设置是否可以被触摸
        popupWindow.setTouchable(true);
        // 设置背景色
        popupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.color.color_white));
        popupWindow.showAtLocation(view, Gravity.BOTTOM, 0, 120);
    }

    /**
     * 退出方法
     */

    private void exitApp() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("醉音乐");
        builder.setIcon(R.mipmap.cache_data_dialog);
        builder.setMessage("确定退出?");
        builder.setPositiveButton("退出程序", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface exitdialog, int which) {
                exitdialog.dismiss();
                finish();
                System.exit(0);
            }
        });
        builder.setNegativeButton("退出账号", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface exitdialog, int which) {
                exitdialog.dismiss();
                mController.deleteOauth(MainActivity.this, SHARE_MEDIA.SINA,
                        new SocializeListeners.SocializeClientListener() {
                            @Override
                            public void onStart() {

                            }

                            @Override
                            public void onComplete(int status, SocializeEntity entity) {
                                if (status == 200) {
                                    Toast.makeText(MainActivity.this, "账号退出成功",
                                            Toast.LENGTH_SHORT).show();
                                    userNm.setText("点击登录");
                                    userIc.setImageDrawable(getResources().getDrawable(R.mipmap.wangfei));
                                } else {
                                    Toast.makeText(MainActivity.this, "账号退出失败",
                                            Toast.LENGTH_SHORT).show();
                                }

                            }
                        });
            }
        });
        builder.setNeutralButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface exitdialog, int which) {
                exitdialog.dismiss();
            }
        });
        //显示弹出框
        builder.create().show();
    }

    /**
     * 定时关闭
     */
    // 弹出TimePicker
    private void alertDialog() {
        final Model model = new Model();
        View myView = null;
        //初始化timePicker的各个部分
        LayoutInflater inflater = LayoutInflater
                .from(MainActivity.this);
        myView = inflater.inflate(R.layout.time_picker_alert_dialog, null);
        model.ensureButton = (TextView) myView.findViewById(R.id.sureBt);
        model.timePicker = (TimePicker) myView.findViewById(R.id.timePicker);
        // 设置为24小时制
        model.timePicker.setIs24HourView(true);
        // 初始化小时
        model.timePicker.setCurrentHour(0);
        // 初始化分钟
        model.timePicker.setCurrentMinute(1);
        model.cancelButton = (TextView) myView.findViewById(R.id.cancelBt);
        final AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).setView(myView).create();
        dialog.show();
        // 确定按钮执行操作
        model.ensureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 将设置的时间转换成秒
                closeHour = ((model.timePicker.getCurrentHour()) * 3600000);
                closeMinutes = ((model.timePicker.getCurrentMinute()) * 60000);
                final int closeTime = closeHour + closeMinutes;
                final int closeTimes = closeTime / 1000;
                countDownTimer = new CountDownTimer(closeTime, 1000) {
                    @Override
                    public void onTick(long millisUntilFinished) {
                        if ((millisUntilFinished / 1000) == closeTimes - 1) {
                            Toast.makeText(MainActivity.this,


                                    "程序将在" + (closeTime / 60000) + "分钟后关闭", Toast.LENGTH_SHORT).show();
                        } else if ((millisUntilFinished / 1000) == 10) {
                            Toast.makeText(MainActivity.this, "10秒后自动退出", Toast.LENGTH_SHORT).show();

                        }
                    }


                    @Override
                    public void onFinish() {
                        System.exit(0);
                    }
                };

                countDownTimer.start();
                dialog.dismiss();
            }
        });

        // 取消按钮退出操作
        model.cancelButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (countDownTimer != null) {
                    countDownTimer.cancel();
                }
                dialog.dismiss();
            }
        });
    }

    class Model {
        private TextView ensureButton;
        private TextView cancelButton;
        private TimePicker timePicker;
    }

    
    /**
     *
     */
    //下一曲
    private void next() {
        if (musicIdle != null) {
            try {
                musicIdle.next();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    //播放
    private void play() {
        if (musicIdle != null) {
            try {
                if (musicIdle.isPlaying()) {
                    musicIdle.pause();
                    playerIv.setImageResource(R.mipmap.btn_playback_play_normal);
                } else {
                    musicIdle.play();
                    playerIv.setImageResource(R.mipmap.btn_playback_pause_normal);
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    //onEvent->进度条->当前进度
    public void onEventMainThread(MyEventBus.CurrentProgress progress) {
        progressTv.setText(LocalListAdapter.formatTime((long) progress.getCurrentProgress()));
    }

    //onEvent->进度条->最大进度
    public void onEventMainThread(MyEventBus.MaxProgress max) {
        maxTv.setText(LocalListAdapter.formatTime((long) max.getMaxProgress()));
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(conn);
        unregisterReceiver(receiver);
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
    }

}
